/*
  This file is a part of hashutils package.
  (c) 2004 Zeljko Vrba <zvrba@globalnet.hr>

  Permission is hereby granted, free of charge, to any person obtaining
  a copy of this software and associated documentation files (the
  "Software"), to deal in the Software without restriction, including
  without limitation the rights to use, copy, modify, merge, publish,
  distribute, sublicense, and/or sell copies of the Software, and to
  permit persons to whom the Software is furnished to do so, subject to
  the following conditions:

  The above copyright notice and this permission notice shall be
  included in all copies or substantial portions of the Software.

  THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
  EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
  MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
  IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
  CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
  TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
  SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <sfio.h>
#include <cdt.h>
#include <mycrypt.h>
#include "halfhash.h"
#include "crypthash.h"
#include "main.h"

static char rcsid[] = "$Id: main.c 2 2007-03-29 14:43:55Z zeljko.vrba $";

/**
   Selected hash and filenames. If filename starts with '$(', then it must
   be processed as a pipe.
   @see \e Main_open_file
*/
static char *Main_hash, *Main_fname[2] = { 0 };

static void register_ciphers(void)
{
	register_cipher(&blowfish_desc);
	register_cipher(&rc2_desc);
	register_cipher(&rc5_desc);
	register_cipher(&safer_k64_desc);
	register_cipher(&safer_sk64_desc);
	register_cipher(&cast5_desc);
}

static void register_hashes(void)
{
	register_hash(&md2_desc);
	register_hash(&md4_desc);
	register_hash(&md5_desc);
	register_hash(&rmd128_desc);

	register_hash(&md2half_desc);
	register_hash(&md4half_desc);
	register_hash(&md5half_desc);
	register_hash(&rmd128half_desc);

	register_hash(&dm_blowfish_desc);
	register_hash(&dm_rc2_desc);
	register_hash(&dm_rc5_desc);
	register_hash(&dm_safer_k64_desc);
	register_hash(&dm_safer_sk64_desc);
	register_hash(&dm_cast5_desc);
}

static char *parse_fname(int argc, char **argv, int *i)
{
	Sfio_t *str;
	int pipe_start = 0;
	
	if(strcmp(argv[*i], "$(")) {
		char *ret = argv[*i];
		++*i;
		return ret;
	}
	pipe_start = *i;

	if(!(str = sftmp(SF_UNBOUND))) {
		sfprintf(sfstderr, "ERROR: can't create temp file, exiting.\n");
		exit(1);
	}
	
	sfprintf(str, "$(");
	while(++*i < argc) {
		if(!strcmp(argv[*i], ")$")) {
			if(*i - pipe_start < 2) {
				sfprintf(sfstderr, "ERROR: $()$ requires at least the command.\n");
				exit(1);
			}
			++*i;				/* advance past )$ */
			sfseek(str, 0, 0);
			return sfreserve(str, -1, 0);
		}
		sfprintf(str, "%s ", argv[*i]);
	}
	sfprintf(sfstderr, "ERROR: unterminated $(\n");
	exit(1);
}

void Main_parse_cmdline(int argc, char **argv)
{
	int i;
	
	/* process options */
	for(i = 1; (i < argc) && (argv[i][0] == '-'); i++) {
		if(!Main_process_option(argc, argv, &i)) {
			Main_usage("ERROR: invalid option.");
		}
	}
	
	/* parse hash */
	if(i < argc) Main_hash = argv[i++];
	else Main_usage("ERROR: Missing HASH argument.");

	/* parse at least 1 filename */
	if(i < argc) Main_fname[0] = parse_fname(argc, argv, &i);
	else Main_usage("ERROR: at least one file must be specified.");

	if(i < argc) Main_fname[1] = parse_fname(argc, argv, &i);
}

void Main_print_hashes(void)
{
	int i, err;

	for(i = 0; hash_descriptor[i].name; i++) {
		sfprintf(sfstderr, "  %s/%u",
				 hash_descriptor[i].name,
				 hash_descriptor[i].hashsize);
		err = hash_descriptor[i].test();
		if(err == CRYPT_OK) {
			sfprintf(sfstderr, "\tself test OK");
		} else if(err == CRYPT_NOP) {
			sfprintf(sfstderr, "\tself test NOT IMPLEMENTED.");
		} else {
			sfprintf(sfstderr, "\tself test FAILED!");
		}
		sfprintf(sfstderr, "\n");
	}
	sfprintf(sfstderr, "Note that md2, md2hx and all DM* ciphers are EXTREMELY SLOW.\n");
}

/**
   If \e fname begins with $(, open it as a pipe. Report an error if open
   doesn't succeed.
*/
Sfio_t *Main_file_open(const char *fname)
{
	Sfio_t *ret;
	
	if(!strcmp(fname, "-")) {
		ret = sfstdin;
	} else if(strncmp(fname, "$(", 2)) {
		if(!(ret = sfopen(NULL, fname, "rt"))) {
			sfprintf(sfstderr, "%s: ERROR: can't open %s: sfopen: %s\n",
					 Main_argv0, fname, strerror(errno));
			exit(1);
		}
	} else if(!(ret = sfpopen(NULL, fname+2, "r"))) {
		sfprintf(sfstderr, "%s: ERROR: can't execute %s: sfpopen: %s\n",
				 Main_argv0, fname, strerror(errno));
		exit(1);
	}
	return ret;
}

int main(int argc, char **argv)
{
	int halg;

	Main_argv0 = argv[0];
	
	/* init crypt library */
	init_half_hashes();
	register_hashes();
	register_ciphers();

	Main_parse_cmdline(argc, argv);
	
	if((halg = find_hash(Main_hash)) < 0) {
		Main_usage("ERROR: invalid hash name.");
	}
	
	/* open files */
	if(Main_fname[1] && !strcmp(Main_fname[0], Main_fname[1])) {
		sfprintf(sfstderr, "%s: ERROR: FROM-FILE and TO-FILE are same.\n", argv[0]);
		return 1;
	}

	Main_process_files(Main_fname[0], Main_fname[1], halg);

	return 0;
}
